<template>
	<div class="signature-container">
		<!-- 签名区域 -->
		<div class="signature-wrapper">
			<vue-esign
				ref="esignRef"
				:width="800"
				:height="400"
				:is-crop="isCrop"
				:line-width="lineWidth"
				:line-color="lineColor"
				:bg-color="canvasBgColor"
				class="signature-canvas"
			/>
			<div v-if="!hasSignature" class="signature-prompt">请在上方区域签名</div>
		</div>

		<!-- 控制栏 -->
		<div class="control-bar">
			<el-row :gutter="10">
				<el-col :span="24">
					<el-tooltip content="清空签名" placement="top">
						<el-button
							icon="el-icon-delete"
							@click="handleReset"
							circle
						></el-button>
					</el-tooltip>

					<el-button
						type="primary"
						icon="el-icon-download"
						@click="handleGenerate"
					>
						生成签名
					</el-button>

					<el-color-picker
						v-model="lineColor"
						size="small"
						:predefine="predefineColors"
					></el-color-picker>

					<el-input-number
						v-model="lineWidth"
						:min="1"
						:max="10"
						size="small"
					></el-input-number>
				</el-col>
			</el-row>
		</div>

		<!-- 预览区域 -->
		<div v-if="imgSrc" class="preview-area">
			<img
				:src="imgSrc"
				class="preview-image"
				style="max-width: 100%"
			>
			<div class="preview-actions">
				<el-button
					type="success"
					icon="el-icon-upload"
					@click="handleUpload"
				>
					提交签名
				</el-button>
				<el-button
					icon="el-icon-download"
					@click="handleDownload"
				>
					下载签名
				</el-button>
			</div>
		</div>
	</div>
</template>

<script>
import vueEsign from 'vue-esign'

export default {
	mounted() {
		console.log('msg2',this.msg)
	},
	components: {
		vueEsign
	},
// 子组件
// 		props: {
// 			msg: {
// 				type: String,
// 				required: false,
// 				default: '默认文本'
// 			}
// 		},
	props: {
		msg: {
			type: String,
			required: true,
			default: '默认文本'
		},
	},
	watch: {
		msg: {
			handler(newVal) {
				console.log('newValMsg', newVal)
				// this.localConfig = JSON.parse(JSON.stringify(newVal)); // 深拷贝避免引用问题
			},
			deep: true // 深度监听对象内部变化
		}
	},
	data() {
		return {
			esignRef: null,
			imgSrc: '',
			lineWidth: 2,
			lineColor: '#000000',
			isCrop: false,
			canvasBgColor: '#f8f9fa',
			predefineColors: [
				'#000000',
				'#e74c3c',
				'#2ecc71',
				'#3498db',
				'#f1c40f'
			]
		}
	},
	computed: {
		hasSignature() {
			return !!this.imgSrc
		}
	},
	methods: {
		// 清空画布
		handleReset() {
			this.$refs.esignRef.reset()
			this.imgSrc = ''
			this.$message.success('画布已清空')
		},

		// 生成签名
		async handleGenerate() {
			console.log('msg3',this.msg)
			try {
				const base64 = await this.$refs.esignRef.generate()
				this.imgSrc = base64
				this.$notify({
					title: '生成成功',
					message: '签名已生成，可下载或提交',
					type: 'success'
				})
				const file = this.base64ToFile(this.imgSrc)
				// 触发自定义事件并传递 formData
				this.$emit('signature-uploaded', file)
				this.$emit('editParentMsg', '子组件传递值(msg)父组件修改值')
			} catch (error) {
				this.$message.error('签名内容为空，请先签名')
			}
		},

		// 下载签名
		handleDownload() {
			const link = document.createElement('a')
			link.href = this.imgSrc
			link.download = `signature_${Date.now()}.png`
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
		},

		// 上传签名
		async handleUpload() {
			try {
				const file = this.base64ToFile(this.imgSrc)
				const formData = new FormData()
				formData.append('file', file)
				formData.append('timestamp', new Date().toISOString())

				// 触发自定义事件并传递 formData
				this.$emit('signature-uploaded', file)
				// 这里调用上传API
				// await this.$axios.post('/api/upload', formData)

				this.$message.success('签名提交成功')
			} catch (error) {
				this.$message.error('签名提交失败')
			}
		},

		// Base64转File
		base64ToFile(dataurl, filename = 'signature') {
			const arr = dataurl.split(',')
			const mime = arr[0].match(/:(.*?);/)[1]
			const suffix = mime.split('/')[1]
			const bstr = atob(arr[1])
			let n = bstr.length
			const u8arr = new Uint8Array(n)
			while (n--) u8arr[n] = bstr.charCodeAt(n)
			return new File([u8arr], `${filename}.${suffix}`, { type: mime })
		}
	}
}
</script>

<style scoped>
.signature-container {
	max-width: 800px;
	margin: 20px auto;
	padding: 20px;
	background: white;
	border-radius: 8px;
	box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.signature-wrapper {
	position: relative;
	border: 1px solid #ebeef5;
	border-radius: 4px;
	margin-bottom: 20px;
}

.signature-canvas {
	background: #f8f9fa;
	display: block;
	width: 100%;
}

.signature-prompt {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	color: #909399;
	font-size: 14px;
	pointer-events: none;
}

.control-bar {
	margin-bottom: 20px;
}

.preview-area {
	margin-top: 20px;
	text-align: center;
}

.preview-image {
	max-width: 100%;
	border: 1px solid #ebeef5;
	border-radius: 4px;
	padding: 10px;
}

.preview-actions {
	margin-top: 15px;
	display: flex;
	gap: 10px;
	justify-content: center;
}

.image-error {
	padding: 20px;
	color: #f56c6c;
	background: #fef0f0;
}
</style>
